package pro.softzhang.algo.lc0;

import pro.softzhang.algo.flag.knowledge.KBackTracking;

import java.util.LinkedList;
import java.util.List;

@KBackTracking
public class LC93_RestoreIpAddresses {
    public static void main(String[] args) {

    }

    /**
     *
     */
    static
    class Solution {
        public List<String> restoreIpAddresses(String s) {
            List<String> r = new LinkedList<>();
            doRestoreIpAddresses(s, 0, 0, "", "", r);
            return r;
        }

        private void doRestoreIpAddresses(String s, int i, int segI, String seg, String ip, List<String> r) {
            if(i == s.length() && segI == 3 && isValidSeg(seg)) {
                r.add(ip + seg);
                return;
            }

            if(i < s.length() && segI <= 3) {
                char ch = s.charAt(i);
                if (isValidSeg(seg + ch)) {
                    doRestoreIpAddresses(s, i + 1, segI, seg + ch, ip, r);
                }

                if (seg.length() > 0 && segI < 3) {
                    doRestoreIpAddresses(s, i + 1, segI + 1, "" + ch, ip + seg + ".", r);
                }
            }
        }

        private boolean isValidSeg(String seg) {
            return Integer.valueOf(seg) <= 255 && (seg.equals("0") || seg.charAt(0) != '0');
        }
    }
}
